<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use DB;
use Route;
use Auth;
use Validator;
use Illuminate\Auth\Events\Logout;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use ThrottlesLogins;use HasApiTokens,Notifiable;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'username';
    }
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->loginValidator($request->all())->validate();

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse();
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return bool
     */
    protected function attemptLogin(Request $request): bool
    {
        return $this->guard()->attempt($this->credentials($request));
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user());
    }

    protected function guard()
    {
        return Auth::guard();
    }

    /**
     * @param Request $request
     * @param $user
     * @return \Illuminate\Http\Response
     */
    protected function authenticated(Request $request, $user)
    {
        $client = DB::table('oauth_clients')->where('password_client', 1)->first();

//        if (!($user->username == '13908036025' || $user->username == 'admin')) {
//            return false;
//        }
        $request->request->add([
            'username'      => $user->username,
            'password'      => $request->get('password'),
            'grant_type'    => 'password',
            'client_id'     => $client->id,
            'client_secret' => $client->secret,
            'scope'         => '*'
        ]);

        $proxy = Request::create('api/token', 'POST');

        Route::dispatch($proxy);

        $user->tokens()->delete();

        return [
            'user' =>$user,
            'accessToken' => $user->createToken($user->username, (array) '*')->accessToken
        ];
    }

    /**
     * @param array $data
     * @return \Illuminate\Validation\Validator
     */
    protected function loginValidator(array $data)
    {
        return \Validator::make($data, [
            $this->username() => 'required|string',
            'password'        => 'required|string',
        ]);
    }

    /**
     * Get the failed login response instance.
     */
    protected function sendFailedLoginResponse()
    {
        return [
            'success' => false,
            'message' => '登录失败,请确认帐号或密码后重试'
        ];
    }

    public function logout(Request $request)
    {
        event(new Logout($request->user()));

        if ($request->wantsJson()) {
            DB::table('oauth_access_tokens')->where('user_id', Auth::id())->delete();
        } else {
            $this->guard()->logout();
            $request->session()->flush();
            $request->session()->regenerate();
            return redirect('/');
        }
    }
}
